/*
 * @Author: 张继伟
 * @Date: 2025-10-29 11:33:58
 * @Description: 
 */
import { User, LoginForm, LoginResponse } from '../types';
import { mockUsers, mockMenus } from '../mock/data';

// 模拟网络延迟
const delay = (ms: number) => new Promise(resolve => setTimeout(resolve, ms));

export const api = {
  // 登录
  login: async (form: LoginForm): Promise<LoginResponse> => {
    await delay(1000);
    
    if (form.username === 'admin' && form.password === '123456') {
      const user = mockUsers.find(u => u.username === form.username);
      if (user) {
        return {
          token: 'mock-jwt-token',
          userInfo: user
        };
      }
    }
    
    throw new Error('用户名或密码错误');
  },

  // 获取用户列表
  getUsers: async (): Promise<User[]> => {
    await delay(500);
    return mockUsers;
  },

  // 添加用户
  addUser: async (user: Omit<User, 'id'>): Promise<User> => {
    await delay(500);
    const newUser: User = {
      ...user,
      id: Math.max(...mockUsers.map(u => u.id)) + 1,
      createTime: new Date().toISOString().split('T')[0]
    };
    mockUsers.push(newUser);
    return newUser;
  },

  // 更新用户
  updateUser: async (id: number, user: Partial<User>): Promise<User> => {
    await delay(500);
    const index = mockUsers.findIndex(u => u.id === id);
    if (index === -1) throw new Error('用户不存在');
    
    mockUsers[index] = { ...mockUsers[index], ...user };
    return mockUsers[index];
  },

  // 删除用户
  deleteUser: async (id: number): Promise<void> => {
    await delay(500);
    const index = mockUsers.findIndex(u => u.id === id);
    if (index === -1) throw new Error('用户不存在');
    
    mockUsers.splice(index, 1);
  },

  // 获取菜单
  getMenus: async (): Promise<any[]> => {
    await delay(300);
    return mockMenus;
  }
};